package com.pmes.utils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Future;

import net.spy.memcached.MemcachedClient;

import org.aspectj.weaver.tools.cache.CacheFactory;

import com.pmes.Constant;
/**
 * 缓存工具类
 * @author liulifeng
 *
 */
public class MemchedUtil {
	
	private static CacheFactory cacheFactory = null;
	
	private static MemcachedClient cache = null;
	
	/**
	 * 将key对应的value值放到缓存中
	 * @param key
	 * @param value
	 * @return
	 */
	public static boolean setValue(String key,Object value,int time){
		if (cache == null) {
			cache = getClient();
		}
		boolean flag = false;
		// 存储数据
        Future fo = cache.set(key, time, value);
        try {
        	flag = (Boolean) fo.get();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	/**
	 * 从缓存中获取值
	 * @param key	缓存中值对应的key
	 * @return
	 */
	public static Object getValue(String key){
		if (cache == null) {
			cache = getClient();
		}
		return cache.get(key);
	}
	
	/**
	 * 根据key删除缓存中key对应值
	 * @param functionType 功能编号
	 * @param key 缓存中值对应的key
	 * @return
	 */
	public static boolean delValue(String key){
		if (cache == null) {
			cache = getClient();
		}
		boolean flag = false;
		// 存储数据
        Future fo = cache.delete(key);
        try {
        	flag = (Boolean) fo.get();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	/**
	 * 获取memcached客户端
	 * @return
	 */
	public static MemcachedClient getClient(){
		try {
			if (cache == null) {
				cache = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return cache;
	}
	public static void main(String[] args) {
		//setValue("type", "test", Constant.CATCH_TIME);
		System.out.println(getValue("type"));
		cache.shutdown();
	}
}
